<template>
  <a-card >
    <a-space class="operator">
      <a-button type="primary" v-on:click="add()">新建</a-button>
      <!-- <a-button >批量操作</a-button> -->
      <a-dropdown>
        <a-menu @click="handleMenuClick" slot="overlay">
          <!-- <a-menu-item key="delete">删除</a-menu-item>
            <a-menu-item key="audit">审批</a-menu-item> -->

          <!-- <a-menu-item key="toLead">
            <a-icon type="upload" />导入
            <input
              type="file"
              title=""
              @change="fileChange"
              v-show="false"
              id="upload"
            />
          </a-menu-item> -->

          <a-menu-item
            v-on:click="batchDel()"
            :disabled="selectedRowKeys.length < 1"
          >
            <a-icon type="delete" />批量删除
          </a-menu-item>
        </a-menu>
        <a-button> 批量操作 <a-icon type="down" /> </a-button>
      </a-dropdown>

      <a-dropdown>
        <a-menu @click="handleMenuClick" slot="overlay">
          <!-- <a-menu-item key="delete">删除</a-menu-item>
            <a-menu-item key="audit">审批</a-menu-item> -->

          <a-menu-item key="toLead">
            <a-icon type="upload" />导入
            <input
              type="file"
              title=""
              @change="fileChange"
              v-show="false"
              id="upload"
            />
          </a-menu-item>

          <a-menu-item key="toOut" v-on:click="alert('暂无')">
            <a-icon type="vertical-align-bottom" />导出
          </a-menu-item>
        </a-menu>
        <a-button> 更多操作 <a-icon type="down" /> </a-button>
      </a-dropdown>
    </a-space>
    <!-- <standard-table
        :columns="columns"
        :dataSource="dataSource"
        :selectedRows.sync="selectedRows"
        @clear="onClear"
        @change="onChange"
        @selectedRowChange="onSelectChange"
      >
        <div slot="description" slot-scope="{ text }">
          {{ text }}
        </div>
        <div slot="action" slot-scope="{ text, record }">
        </div>
        <template slot="statusTitle">
          <a-icon @click.native="onStatusTitleClick" type="info-circle" />
        </template>
      </standard-table> -->
    <!-- <div class="table-adv"> -->
    <advance-table
      :columns="columns"
      :data-source="dataSource"
      :row-selection="{
        selectedRowKeys: selectedRowKeys,
        onChange: onSelectChange,
      }"
      :title="tableTitle"
      :loading="loading"
      rowKey="id"
      @search="onSearch"
      @refresh="onRefresh"
      :format-conditions="true"
      @reset="onReset"
      :bordered="true"
      :scroll="{ x: 1000 }"
      :pagination="false"
    >
      <!-- <template slot="statusTitle">
        状态<a-icon style="margin: 0 4px" type="info-circle" />
      </template> -->
      <template slot="phoneMessage" slot-scope="{ text }">
        <div
          v-for="(item, index) in JSON.parse(text)"
          :key="index"
          :title="`工商电话:${item.phone}\n查微信昵称:${item.wechatName}\n加微信情况:${item.situation}`"
          class="over-one"
          v-show="item.phone || item.wechatName || item.situation"
        >
          <span>
            工商电话:{{ item.phone }} 查微信昵称:{{
              item.wechatName
            }}
            加微信情况:{{ item.situation }}
          </span>
        </div>
      </template>


     <template slot="followUp" slot-scope="{ text }">
        <span
          v-for="(item, index) in JSON.parse(text)"
          :key="index"
          :title="`日期:${item.date}\n跟进情况:${item.remark}`"
        >  
           日期：{{item.date}}&nbsp;&nbsp;
           跟进情况：{{item.remark}}
           <br/>
        </span>
           

      </template>

      <template slot="annalsPhone" slot-scope="{ text }">
        <span
          v-for="(item, index) in JSON.parse(text)"
          :key="index"
          :title="item.phone"
          v-show="item.phone"
        >
          {{ item.phone }} <br />
        </span>
      </template>


      <template slot="annalsEmail" slot-scope="{ text }">
        <span
          v-for="(item, index) in JSON.parse(text)"
          :key="index"
          :title="item.email"
          v-show="item.email"
        >
          {{ item.email }} <br />
        </span>
      </template>

      <template slot="enterpriseName" slot-scope="{ text }">
        {{ text.enterpriseName
        }}<a-tag
          style="margin-left: 5px"
          v-show="text.top_time"
          v-on:click="operate('onTop', text, true)"
          >置顶</a-tag
        >
      </template>

      <template slot="operation" slot-scope="{ text }">
        <div class="operation">
          <a href="javascript:;" v-on:click="operate('edit', text)">编辑</a>

          <a-popconfirm
            :title="`确定要${text.top_time ? '取消' : ''}置顶吗?`"
            @confirm="() => operate('onTop', text)"
          >
            <a href="javascript:;" v-show="text.top_time">取消置顶</a>
            <a href="javascript:;" v-show="!text.top_time">置顶</a>
          </a-popconfirm>
          <a-popconfirm
            :title="`确定要删除吗?`"
            @confirm="() => operateDel(text)"
          >
            <a href="javascript:;">删除</a>
          </a-popconfirm>
        </div>
      </template>
    </advance-table>

    <div class="show-right">
      <a-pagination
        :current="page"
        :pageSize="pageSize"
        :total="total"
        :showSizeChanger="true"
        :showLessItems="true"
        :showQuickJumper="true"
        :pageSizeOptions="['10', '20', '50', '100', '500', ...total.toString()]"
        :scroll="{ x: 1300 }"
        :showTotal="
          (total, range) => `第 ${range[0]}-${range[1]} 条，总计 ${total} 条`
        "
        @change="onPageChange"
        @showSizeChange="onSizeChange"
        :loading="loading"
      >
        <template slot="buildOptionText" slot-scope="props">
          <span v-if="props.value == total">全部</span>
          <span v-else>{{ props.value }}条/页</span>
        </template>
      </a-pagination>
    </div>
    <a-modal
    
      v-model="visible"
      title="确定要导入吗？"
      ok-text="确认"
      cancel-text="取消"
      :confirmLoading="confirmLoading"
      @ok=" () => uploadOp()"
      @cancel="() => (visible = false)"
    >
      <a-form :form="uploadForm" class="form">
        <a-row>
          <a-col :xl="{ span: 10 }" :sm="24">
            <a-form-item label="起始工作表">
              <a-input
                placeholder="起始工作表"
                v-decorator="[
                  'startSheet',
                  {
                    rules: [
                      { max: 255, message: '不得超过255个字符' },
                      {
                        validator: checkNum,
                        message: '只能为正整数',
                        trigger: 'change',
                      },
                    ],
                    initialValue: '',
                  },
                ]"
              />
            </a-form-item>
          </a-col>

          <a-col :xl="{ span: 10, offset: 3 }" :sm="24">
            <a-form-item label="结束工作表">
              <a-input
                placeholder="结束工作表"
                v-decorator="[
                  'endSheet',
                  {
                    rules: [
                      { max: 255, message: '不得超过255个字符' },
                      {
                        validator: checkNum,
                        message: '只能为正整数',
                        trigger: 'change',
                      },
                    ],
                    initialValue: '',
                  },
                ]"
              />
            </a-form-item>
          </a-col>
        </a-row>
      </a-form>
    </a-modal>
    <!-- </div> -->
    <!-- <router-view> </router-view> -->
  </a-card>
</template>

<script>
// import StandardTable from "@/components/table/StandardTable";
import AdvanceTable from "@/components/table/advance/AdvanceTable";
import {
  teachingUpload,
  teachingList,
  teachingGoupBy,
  teachingUpdate,
} from "@/services/teaching-culture";

const checkNum = (rule, value, callback) => {
  if (value != "") {
    if (!/^([1-9][0-9]*)?$/.test(value)) {
      callback(new Error(""));
    } else {
      callback();
    }
  } else {
    callback();
  }
};

export default {
  name: "TeachingCulture",
  components: { AdvanceTable },
  data() {
    return {
      loading: false, //表格是否加载中
      page: 1, //第几页
      pageSize: 10, //一页多少条
      total: 0, //总共多少条
      tableTitle: " ", //表格标题
      keyWord: {}, //关键词搜索
      selectedRowKeys: [], //批量操作
      checkNum: checkNum,
      columns: [
        //显示什么列
        {
          title: "公司名称",
          returnField: "like-teaching-enterpriseName",
          scopedSlots: { customRender: "enterpriseName" },
          width: 400,
          searchAble: true,
        },
        {
          title: "公司分类",
          dataIndex: "sheetName",
          width: 200,
          returnField: "equal-teaching-sheetName",
          dataType: "select",
          searchAble: true,
          search: {
            selectOptions: [],
          },
        },
        {
          title: "注册地址",
          dataIndex: "registeredAddress",
          returnField: "like-teaching-registeredAddress",
          width: 300,
          ellipsis: true,
          
        },
        {
          title: "经营范围",
          returnField: "like-teaching-scopeBusiness",
          dataIndex: "scopeBusiness",
          ellipsis: true,
          width: 400,
        },
        {
          title: "成立日期",
          dataIndex: "setUpDate",
          returnField: "like-teaching-setUpDate",
          ellipsis: true,
          width: 150,
          dataType: "date",
        },
        {
          title: "核准日期",
          dataIndex: "approvedDate",
          returnField: "like-teaching-approvedDate",
          ellipsis: true,
          width: 150,
          dataType: "date",
        },
        {
          title: "法人",
          returnField: "like-teaching-legalPerson",
          dataIndex: "legalPerson",
          ellipsis: true,      
          width: 150,
        },
        {
          title: "沟通跟进情况",
          returnField: "like-teaching-followUp",
           scopedSlots: { customRender: "followUp" },
          dataIndex: "followUp",
          width: 300,
          ellipsis: true,
        },
        {
          title: "工商手机号",
          dataIndex: "phoneMessage",
          returnField: "like-teaching-phoneMessage",

          scopedSlots: { customRender: "phoneMessage" },
          width: 300,
        },
        {
          title: "年报电话",
          dataIndex: "annalsPhone",
          returnField: "like-teaching-annalsPhone",

          scopedSlots: { customRender: "annalsPhone" },
          width: 300,
        },
        {
          title: "年报邮箱",
          dataIndex: "annalsEmail",
          returnField: "like-teaching-annalsEmail",
          scopedSlots: { customRender: "annalsEmail" },
          width: 300,
        },
        // {
        //   // searchAble: true,
        //   dataIndex: "status",
        //   dataType: "select",
        //   slots: { title: "statusTitle" },
        //   scopedSlots: { customRender: "status" },
        //   search: {
        //     selectOptions: [
        //       { title: "已下单", value: 1 },
        //       { title: "已付款", value: 2 },
        //       { title: "已审核", value: 3 },
        //       { title: "已发货", value: 4 },
        //     ],
        //   },
        // },
        // {
        //   title: "发货",
        //   // searchAble: true,
        //   dataIndex: "send",
        //   dataType: "boolean",
        //   scopedSlots: { customRender: "send" },
        //   search: {
        //     switchOptions: {
        //       checkedText: "开",
        //       uncheckedText: "关",
        //     },
        //   },
        // },
        // {
        //   title: "审核时间",
        //   dataIndex: "auditTime",
        //   dataType: "time",
        // },
        {
          title: "操作",
          fixed: "right",
          notSearch: true,
          width: 180,
          scopedSlots: { customRender: "operation" },
        },
      ],
      dataSource: [], //显示的数据
      conditions: {}, //条件
      visible: false, //导入弹出层
      fileFormData: {}, //文件上传预备
      confirmLoading:false, //导入按钮lading
      uploadForm: this.$form.createForm(this),
    };
  },
  authorize: {
    operate: "编辑",
    add: "添加",
    operateDel: "删除",
    batchDel: "删除",
  },
  created() {
    // this.getColumns()
    this.tableLoad(); //表格查询
  },
  methods: {
    onSearch(conditions, searchOptions) {
      // console.log(searchOptions);
      // console.log(conditions);
      this.keyWord = conditions;
      this.page = 1;
      // this.conditions = conditions;
      this.tableLoad();
    },
    onSizeChange(current, size) {
      this.page = 1;
      this.pageSize = size;
      this.tableLoad();
    },
    onRefresh(conditions) {
      this.conditions = conditions;
      this.tableLoad();
    },
    onReset(conditions) {
      this.conditions = conditions;
      this.tableLoad();
    },
    onPageChange(page, pageSize) {
      // alert()
      this.page = page;
      this.pageSize = pageSize;
      this.tableLoad();
    },

    fileChange(e) {
      const { uploading } = this;
      let files = e.target.files[0];
      let formData = uploading(files, "excel", "teaching_culture");
      if (formData) {
        //  teachingUpload
        // this.$confirm({
        //   title: "确定要导入吗?",
        //   content: 'When clicked the OK button, this dialog will be closed after 1 second',
        //   async onOk() {

        //   },
        // });
        this.fileFormData = formData;
        this.visible = true;

        var file = document.getElementById("upload");
        file.value = ""; //重置了file的outerHTML
      }
      // //console.log(formData);
    },
    uploadOp() {
      const { $message, uploadForm, tableLoad } = this;
      uploadForm.validateFields(async (err) => {
        if (err) {
          $message.error("信息填写有误");
          return;
        } else {
          $message.loading({ content: "导入中", key: "loading" });
         
          // fileFormData.append("")
          let sheetObj = uploadForm.getFieldsValue();

          if (sheetObj["startSheet"] && sheetObj["endSheet"]) {
            if (sheetObj["endSheet"] > sheetObj["startSheet"]) {
              $message.error("起始工作表不能大于结束工作表");
              return;
            }
          }
         this.confirmLoading = true
          for (let key in sheetObj) {
            this.fileFormData.append(key, sheetObj[key]);
          }
          // console.log(sheetObj);
          let res = await teachingUpload(this.fileFormData);
          if (res.code == 200) {
            $message.success({
              content: "导入成功",
              key: "loading",
              duration: 2,
            });
          }
          this.visible = false;
          this.fileFormData = "";
          this.page = 1;
          this.confirmLoading = false  //按钮loading
           tableLoad();
        }
      });
    },
    add() {
      this.$router.push("/enterprise/teachingAdd");
    },
    async teachingGoupByLoad() {
      this.columns[1].loading = true;
      let teachingGoupByList = await teachingGoupBy({});
      this.columns[1].search.selectOptions = teachingGoupByList.data;
      this.columns[1].loading = !this.columns[1].loading;
    },

    async tableLoad() {
      this.loading = true;
      const { page, pageSize, keyWord, teachingGoupByLoad } = this;

      // console.log(teachingGoupByList);
      teachingGoupByLoad(); //分类查询

      let teaching = await teachingList({
        page: page,
        pageSize: pageSize,
        keyWord: keyWord,
      });
      //console.log(teaching);
      const { list, total } = teaching.data;
      this.dataSource = list;
      this.total = total;
      this.loading = false;
    },
    async operate(key, data, top = false) {
      const { sysTime, $message, tableLoad } = this;
      switch (
        key //置顶操作
      ) {
        case "onTop":
          $message.loading({ content: "修改中", key: "loading" });
          let res = await teachingUpdate({
            formData: { top_time: data.top_time && !top ? null : sysTime() },
            id: data.id,
          });
          if (res.code == 200) {
            $message.success({
              content: "修改成功",
              key: "loading",
              duration: 2,
            });
            tableLoad();
          }

          break;

        case "edit":
          this.$router.push({
            path: "/enterprise/teachingEdit",
            query: { teaching_id: data.id },
          });

          break;
      }
    },
    async operateDel(data) {
      const { sysTime, $message, tableLoad } = this;

      $message.loading({ content: "删除中", key: "loading" });
      let res = await teachingUpdate({
        formData: { delete_time: sysTime() },
        id: data.id,
      });
      if (res.code == 200) {
        $message.success({
          content: "删除成功",
          key: "loading",
          duration: 2,
        });
        tableLoad();
      }
    },
    batchDel() {
      const { sysTime, $message, tableLoad, $confirm, selectedRowKeys } = this;

      $confirm({
        title: "确定要删除吗?",
        async onOk() {
          $message.loading({ content: "删除中", key: "loading" });
          let res = await teachingUpdate({
            formData: { delete_time: sysTime() },
            id: selectedRowKeys,
          });
          if (res.code == 200) {
            $message.success({
              content: "删除成功",
              key: "loading",
              duration: 2,
            });
            tableLoad();
          }
        },
      });
    },
    
    onSelectChange(selectedRowKeys) {
      this.selectedRowKeys = selectedRowKeys;
    },
    // async batchDel() {
    //   const { sysTime, $message, tableLoad } = this;
    //   $message.loading({ content: "删除中", key: "loading" });
    //   let res = await teachingUpdate({
    //     formData: { delete_time: sysTime() },
    //     id: this.selectedRowKeys,
    //   });
    //   if (res.code == 200) {
    //     $message.success({
    //       content: "删除成功",
    //       key: "loading",
    //       duration: 2,
    //     });
    //     tableLoad();
    //   }
    // },
    handleMenuClick(e) {
      if (e.key === "toLead") {
        //导入
        let upload = document.getElementById("upload");

        upload.click();
      }
    },
  },
};
</script>

<style lang="less" scoped>
.table-adv {
  max-width: 100%;
  // border: 1px solid blue;
  overflow: auto;
  white-space: nowrap;
}

.show-right {
  float: right;
  margin-top: 10px;
}
.operation {
  display: flex;
  justify-content: space-between;
}
.over-one {
  overflow: hidden;
  white-space: nowrap;
  text-overflow: ellipsis;
}
</style>
